/*
 * @lc app=leetcode.cn id=1124 lang=javascript
 *
 * [1124] 表现良好的最长时间段
 */

// @lc code=start
/**
 * @param {number[]} hours
 * @return {number}
 */
var longestWPI = function(hours) {
  let preSum = new Array(hours.length + 1).fill(0);
  for(let i = 0; i < hours.length; i++) {
      preSum[i + 1] = preSum[i] + (hours[i] > 8 ? 1 : -1);
   }
   let stack = [0];
   for(let i = 1; i < preSum.length; i++) {
       if (preSum[i] < preSum[stack[stack.length - 1]]) stack.push(i);
   }
   let max = 0;
   for(let i = preSum.length - 1; i > max; i--) {
       while(stack.length && preSum[i] > preSum[stack[stack.length - 1]]) {
           max = Math.max(max, i - stack.pop());
       }
   }
   return max;
};
// @lc code=end

